import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'
export const _MENU_ROUTERS: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('@/views/home/indexView.vue'),
    meta: {
      title: '首页',
      icon: 'i-ep-HomeFilled'
    }
  },
  {
    path: '/set',
    component: () => import('@/views/set/indexView.vue'),
    meta: {
      title: '设置'
    }
  },
  {
    path: '/list/manage',
    component: () => import('@/views/listManage/indexView.vue'),
    meta: {
      title: '列表管理'
    }
  },
  {
    path: '/menus/manage',
    component: () => import('@/views/menusManage/indexView.vue'),
    meta: {
      title: '菜单管理'
    }
  },
  {
    path: '/other/manage',
    component: () => import('@/views/other/indexView.vue'),
    meta: {
      title: '其他管理'
    }
  },
  {
    path: '/role/manage',
    component: () => import('@/views/roleManage/indexView.vue'),
    meta: {
      title: '角色管理'
    }
  },
  {
    path: '/user/manage',
    component: () => import('@/views/userManage/indexView.vue'),
    meta: {
      title: '用户管理'
    }
  }
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/indexView.vue'),
      meta: {
        title: '用户登录'
      }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/layout/indexView.vue'),
      meta: {
        title: '布局'
      },
      children: _MENU_ROUTERS
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')

  // token 存在  去登录页面， 拦截去首页
  if (token) {
    const { nickname, loginSuccess } = useUserStore()
    if (!nickname) {
      // 获取用户信息
      const resp = await axios.get('/api/user/info', { params: { token } })
      const { code, data, message } = resp.data
      if (code === 10000) {
        loginSuccess(data)
        // 重新获取用户信息， 路由也需要重新跳转
        next({ ...to, replace: true })
      } else {
        localStorage.removeItem('token')
        next('/login')
        ElMessage.error(message)
      }
    } else {
      // 已经登录，用户信息
      if (to.path === '/login') {
        next('/')
      } else {
        next()
      }
    }
  } else {
    if (to.path !== '/login') {
      next('/login')
    } else {
      next()
    }
  }

  // token不存在  访问非登录页面  拦截去登录

  // 正常访问

  // 已经登录     去登录页

  // 没有登录     去非登录页
})

export default router
